package com.file;

import com.utils.FileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 预览文件
 */
@WebServlet(name = "PreviewFile", urlPatterns = {"/PreviewFile"})
public class PreviewFile extends HttpServlet {
    private final String DOC = ".doc";
    private final String DOCX = ".docx";
    private final String PDF = ".pdf";
    private final String PNG = ".png";
    private final String JPG = ".jpg";
    private final String JPEG = ".jpeg";
    private final String GIF = ".gif";
    private final String XLS = ".xls";
    private final String XLSX = ".xlsx";
    private final String MP4 = ".mp4";
    private final String OGV = ".ogv";
    private final String WEBM = ".webm";

    /**
     * 将文件转为Html
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        String fileName = new String(req.getParameter("file"));
        String realPath = FileUtil.BASE_PATH + File.separator + fileName;
        File file = new File(realPath);
        byte[] bytes = FileUtil.getBytes(file);
        int suffixIndex = fileName.lastIndexOf(".");
        try {
            if(DOC.equals(fileName.substring(suffixIndex))){
                FileUtil.word2003ToHtml(bytes, resp);
            }else if(DOCX.equals(fileName.substring(suffixIndex))){
                FileUtil.word2007ToHtml(bytes, resp);
            }else  if(PDF.equals(fileName.substring(suffixIndex))){
                FileUtil.pdf2Html(bytes, resp);
            }else{
                //如果文件类型既不是pdf也不是word】，就直接放弃吧
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
